package com.bjor.models;

import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;

public class LevelPlan {
	
	private XYMultipleSeriesDataset dataset;
	private int minutesDuration;
	private Gender gender;
	private float weight;
	private Level level;
	private final double timeUnit = 0.5; // minutes
	
	
	// TODO: Strings from shared pref!!
	public LevelPlan (int minutesDuration, Gender gender, float weight, Level level)
	{
		this.minutesDuration = minutesDuration;
		this.gender = gender;
		this.weight = weight;
		this.level = level;
		
		
	}

	public XYMultipleSeriesDataset getDataSet()
	{
		// 500 : ml in drink, 0.05: alcoholic percentage, 0.9 : g/ml etyl alcohol,
		// 10 : g alcohol in std drink.
		
		double alcoholInDrink = 500*0.05*0.9;
		double drinkToStdDrinkRatio = alcoholInDrink / 10;
		
		double timeToLower = minutesDuration*level.ratioToLower;	//minutes for ascend to lower limit of BAC
		
		double stdDrinksToLower = (level.lowerBAC + (gender.MR * timeToLower/60))
								 * gender.BW * weight / (0.806*1.2);
		
		double drinksToLower = stdDrinksToLower * drinkToStdDrinkRatio;
		
		int timeUnitsBetweenDrinksLower = (int)(timeToLower / (double)(drinksToLower * timeUnit));
		
		double slopeToLower = (level.lowerBAC - 0) / (timeToLower - 0);
		
		dataset = new XYMultipleSeriesDataset();
	    XYSeries bacSeries = new XYSeries("BAC per time");
	    XYSeries drinkSeries = new XYSeries("Open drink");
		
	    double timeToLowerLastDrink = ((int)timeToLower % timeUnitsBetweenDrinksLower);
	    
	    for(int i = 0; i < (int)timeToLowerLastDrink / timeUnit; i++)
	    {
	    	double x = i * timeUnit / 60;
	    	double y = x * slopeToLower;
	    	
	    	bacSeries.add( x, y );
	    	
	    	if ( i % timeUnitsBetweenDrinksLower == 0 )
	    		drinkSeries.add(x, y);
	    }
		
		double timeToUpper = minutesDuration - timeToLowerLastDrink;
		
		double slopeToUpper = (level.upperBAC - level.lowerBAC) 
				/ (minutesDuration - (minutesDuration * level.ratioToLower - timeToLowerLastDrink));
		
		double stdDrinksToUpper = (level.upperBAC + (gender.MR * timeToUpper/60))
				 * gender.BW * weight / (0.806*1.2);
		
		double drinksToUpper = stdDrinksToUpper * drinkToStdDrinkRatio;
		
		int timeUnitsBetweenDrinksUpper = (int)(timeToUpper / (double)(drinksToUpper * timeUnit));
	    
		for(int i = (int) (timeToLowerLastDrink / timeUnit) ; i < minutesDuration / timeUnit; i++)
	    {
	    	double x = i * timeUnit / 60;
	    	double y = x * slopeToUpper;
	    	
	    	bacSeries.add( x, y );
	    	
	    	if ( i % timeUnitsBetweenDrinksUpper == 0 )
	    		drinkSeries.add(x, y);
	    }	
		
	    dataset.addSeries(bacSeries);
	    dataset.addSeries(drinkSeries);
	    
	    return dataset;		
		
	}

}
